'use strict'

let fs = require('fs');

class CsvParser {
    constructor() {
    }

    parseFile(fileName) {
        return this.parseText(fs.readFileSync(fileName).toString());
    }

    parseText(text) {
        let lines = text.split('\n').map(line => {
            line = line.trim()
            if ( line.endsWith(',') ) {
                line = line.slice(0, line.length - 1);
            }

            return line;
        }).filter(line => line.length > 0);

        let cells = lines.map(line => {
            return line.split(',').map(cell => {
                if ( cell.startsWith('"') ) {
                    cell = cell.slice(1, cell.length - 1);
                }
                
                return cell;
            });
        });

        let headers = cells[0];
        let dataLines = cells.slice(1);

        return this.parseRecords(headers, dataLines);
    }

    parseRecords(headers, dataLines) {
        return dataLines.map(dataLine => {
            let record = Object.create(null);
            headers.forEach((fieldName, fieldIndex) => {
                record[fieldName] = dataLine[fieldIndex];
            });

            return record;
        });
    }
}

module.exports = {
    CsvParser
};
